<template>
  <div class="stats-panel stats-panel-trend" ref="trend" style="background:none">
    <div class="plan-trend-chart">
      <h3>{{$t('report.performanceChart.name')}}
        <el-popover trigger="hover">
          <ul>
            <li>{{ $t('report.product.title12') }}</li>
            <li>{{ $t('report.product.title13') }}</li>
          </ul>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
      <!-- <div class="stats-form-group">
        <select id="team" @change="chooseTeam">
          <option value="">全部</option>
          <option v-for="team in teams" :key="team.id" :value="team.id">{{team.name}}</option>
        </select>
      </div> -->

      <div class="charts-search-block charts-search">
        <div  class="charts-search-block-content">
          <div class="charts-search-item">
            <label>{{$t('common.base.department')}}：</label>
            <biz-team-select class="stats-team-select biz-team-select" is-auto-select-child collapse multiple :value="tag" @input="chooseTeam" :fetch-func="fetchTeam"/>
          </div>
          <div class="charts-search-item" style="margin-bottom:0;">
            <label>{{$t('common.label.timeRange')}}：</label>
            <bbx-date-period
              v-model="periodValue"
              value-format="x"
              range
              @change="chooseDate"
            />
            <div class="error-row">
              <div class="start">
                <span v-show="!periodValue.startTime">{{$t('common.validate.selectStartNode', {node: typeMap[periodValue.type]})}}</span>
              </div>
              <div class="end">
                <span v-show="!periodValue.endTime">{{$t('common.validate.selectEndNode', {node: typeMap[periodValue.type]})}}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="charts-search-btn">
          <el-button type="plain-third" @click="handlerResetClick">
            {{ $t('common.base.reset') }}
          </el-button>
          <el-button type='primary' @click="handlerSearchClick">
            {{ $t('common.base.search') }}
          </el-button>
        </div>
      </div>
    </div>
    <div class="stats-panel-body" style="background:#fff;">
      <div id="trend"></div>
    </div>

    <div class="stats-trend-table-wrap" v-show="showTable">
      <div class="stats-trend-table-bar">
        <h5>{{$t('common.label.taskList')}}</h5>

        <button class="btn btn-primary btn-sm" @click="exportData" style="margin-right: 5px;" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button>
        <button class="btn btn-primary btn-sm" @click="exportAllData" style="margin-right: 5px;" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button>
        <button class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.hide') }}</button>
      </div>
      <base-table class="stats-table"
                  :rows="tableData.list || []" 
                  :columns="columns"
                  :disable-select="true"
                  :limit="10"
      ></base-table>
    </div>
  </div>
</template>

<script>
/* global moment, _init_data*/
import { isOpenData, openAccurateTab } from '@src/util/platform';
import _ from 'lodash';
import qs from 'src/util/querystring';
import http from 'src/util/HttpUtil';

import echarts from 'packages/Echarts'

import TaskStateEnum from '@model/enum/TaskStateEnum';
import { checkButtonDisplayed } from '@src/util/dom';
let trend = null;
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { dayTimeStart, dayTimeEnd, nearDateBy, formatDate, FormatTemplate, firstDayOfMonth, lastDayOfMonth, firstDayOfWeek, lastDayOfWeek, firstDayOfYear, lastDayOfYear} from 'pub-bbx-utils';
import BbxDatePeriod from '@src/component/Bbx/DatePeriod'
import { t } from '@src/locales'
const typeMap = {
  date: t('common.time.date'),
  week: t('common.time.week'),
  month: t('common.time.month'),
  quarter: t('common.time.quarter'),
  year: t('common.time.year'),
}
export default {
  name: 'plan-trend-chart',
  components: {
    BbxDatePeriod,
  },
  props: {
    chartType: {
      type: String,
      default: ''
    }
  },
  data(){
    return {
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      tag: [],
      // teams: [],
      trendStartTime: '',
      trendEndTime: '',
      teamId: '',
      tableData: {},
      columns: this.buildColumns(),
      showTable: false,
      state: '',
      day: '',
      periodValue: {
        startTime: null,
        endTime: null,
        type: 'date'
      },
      typeMap
    };
  },
  methods: {
    resetSearchTime(){
      this.periodValue = {
        startTime: +nearDateBy(7),
        endTime: +dayTimeEnd(nearDateBy(1)),
        type: 'date'
      }
    },

    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    exportAllData(){
      const { periodValue, teamId } = this
      const { startTime, endTime } = periodValue
      let model = {
        exportAll: '1',
        tagId: teamId,
        timeStart: startTime || undefined,
        timeEnd: endTime || undefined,
      }

      window.location.href = `/api/report/outside/stats/plan/trendDetail/export?${ qs.stringify(model)}`;

      this.exportTrack(true)
    },
    exportData(){
      let model = {
        state: this.state,
        tagId: this.teamId,
      }

      if(this.day){
        let {timeStart, timeEnd} = this.formatTime(this.day)
        model.timeStart = timeStart;
        model.timeEnd = timeEnd;
      } 
      
      window.location.href = `/api/report/outside/stats/plan/trendDetail/export?${ qs.stringify(model)}`;

      this.exportTrack(false)
    },
    exportTrack(isExportAll) {
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.chartType,
      }, '*')
    },
    chooseDate(start, end) {
      this.$emit('trackEvent', 'chooseDate');
      this.renderTrend();
    },
    chooseTeam(value){
      this.$emit('trackEvent', 'chooseTeam');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      let tag = value
      this.tag = value;
      this.teamId = tag.map(item => {return item.id}).join(',');
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TEAM', this.$track)
    },

    // 初始化图表
    initTrend() {
      trend = echarts.init(document.getElementById('trend'));
      trend.on('click', event => {
        if(event.data.value == 0) return;

        let origin = event.data._origin;
        let state = 'created';
        let day = formatDate(origin.statisticsTime, FormatTemplate.date);

        if(event.seriesName == t('task.setting.taskTypeSetting.flow.flowMap.finish.name')) state = 'finished';

        this.state = state;
        this.day = day;

        this.renderTable(day, state);
      });
      
    },
    async renderTrend() {
      try{
        const {startTime, endTime} = this.periodValue
        if(!startTime || !endTime) return
        this.showTable = false;
        let instance = this.$loading.show(this.$el)

        let data = await this.fetchTrendData();
        instance.hide();

        trend.clear();
        trend.setOption(this.getTrendOption(data.created, data.completed))
      }catch(err){
        console.log(err)
      }
    },
    getTrendOption(created, completed){
      let colors = ['#5793f3', this.getThemeColor, '#675bba'];

      let created_xAxis = [];
      let created_data = [];
      created.forEach(item =>{
        created_xAxis.push(formatDate(item.statisticsTime, this.periodValue.type))
        created_data.push({
          name: t('report.callConsultChart.addWorkOrder'),
          value: item.count,
          _origin: item
        })
      });

      let completed_xAxis = [];
      let completed_data = [];
      completed.forEach(item =>{
        completed_xAxis.push(formatDate(item.statisticsTime, this.periodValue.type));
        completed_data.push({
          name: t('task.setting.taskTypeSetting.flow.flowMap.finish.name'),
          value: item.count,
          _origin: item
        });
      });

      return {
        color: colors,
        grid: {
          top: 70,
          bottom: 40,
          left: 80,
          right: 50
        },
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: t('report.performanceChart.name'),
            }
          },
          right: 40
        },
        legend: {
          data:[t('report.callConsultChart.addWorkOrder'), t('task.setting.taskTypeSetting.flow.flowMap.finish.name')],
          top: 5,
          align: 'left'
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[1]
              }
            },
            axisPointer: {
              label: {
                // 解决翻译冲突时需要注意，此处逻辑有修改
                formatter (params) {

                  const labelVal = params.seriesData.length ? params.seriesData[0]?.data?.value : '';
                  return `${t('task.setting.taskTypeSetting.flow.flowMap.finish.name')}  ${ params.value } ${ labelVal ? (labelVal +  ' ' + t('task.components.taskAllotModal.one')) : ''}`;
                }
              }
            },
            data: created_xAxis
          },
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[0]
              }
            },
            axisPointer: {
              label: {
                // 解决翻译冲突时需要注意，此处逻辑有修改
                formatter (params) {
                  const labelVal = params.seriesData.length ? params.seriesData[0]?.data?.value : '';
                  return `${t('report.callConsultChart.addWorkOrder')}  ${ params.value } ${ labelVal ? (labelVal +  ' ' + t('task.components.taskAllotModal.one')) : ''}`;
                }
              }
            },
            data: completed_xAxis
          }
        ],
        yAxis: [{
          type: 'value'
        }],
        series: [
          {
            name:t('report.callConsultChart.addWorkOrder'),
            type:'line',
            smooth: true,
            data: created_data,
            xAxisIndex: [1],
            itemStyle: { normal: {label : {show: true}}}
          },
          {
            name:t('task.setting.taskTypeSetting.flow.flowMap.finish.name'),
            type:'line',
            smooth: true,
            data: completed_data,
            xAxisIndex: [0],
            itemStyle: { normal: {label : {show: true}}}
          }
        ]
      }
    },

    getDimension(){
      // 统计维度: 0:天 1:周 2:月 3:季度 4:年
      let dimension = 0;
      switch(this.periodValue.type){
        case 'day': dimension = 0;break;
        case 'week': dimension = 1;break;
        case 'month': dimension = 2;break;
        case 'quarter': dimension = 3;break;
        case 'year': dimension = 4;break;
      }
      return dimension;
    },

    fetchTrendData(){
      const { periodValue, teamId } = this
      const { startTime, endTime } = periodValue
      
      let params = {
        timeStartL: startTime,
        timeEndL: endTime,
        tagId: teamId,
        dimension: this.getDimension(),
      }

      return http.get('/api/report/outside/stats/plan/trend', params)
    },

    async renderTable(day, state){
      try {
        let instance = this.$loading.show(this.$el)
        let data = await this.fetchTableData(day, state);
        instance.hide();

        this.$nextTick(() => {
          this.tableData = data;
          this.showTable = true;
        })
      } catch (error) {
        console.log(error)
      }
    },
    fetchTableData(day, state){
      let {timeStart, timeEnd} = this.formatTime(day)
      let params = {
        timeStart,
        timeEnd,
        tagId: this.teamId,
        state
      }

      return http.post('/api/report/outside/stats/plan/trendDetail', params)
    },
    formatTime(day) {
      let timeEnd = ''
      let timeStart = ''
      switch (this.periodValue.type){
          case 'week': 
            timeStart = +firstDayOfWeek(day)
            timeEnd = +lastDayOfWeek(day);
            break;
          case 'month': 
            timeStart = +firstDayOfMonth(day)
            timeEnd = +lastDayOfMonth(day);
            break;
          case 'year': 
            timeStart = +firstDayOfYear(day);
            timeEnd = +lastDayOfYear(day);
            break;
          default: 
            timeStart = +dayTimeStart(day)
            timeEnd = +dayTimeEnd(day);
      }
      return {timeStart, timeEnd}
    },
    buildColumns(){
      return [
        {
          label: t('common.base.serialNumber'),
          field: 'taskNo',
          width: 140,
          render: (h, row, field) =>{
            let data = {
              attrs: {
                href: `/task/view/${row.taskId}`
              },
              on: {
                click: event => {
                  event.preventDefault();
                  let fromId = window.frameElement.getAttribute('id');
                  // this.$platform.openTab({
                  //   id: `taskView_${ row.taskId}`, 
                  //   title: `工单${row.taskNo}`,
                  //   close: true, 
                  //   url: `/task/view/${ row.taskId}`,
                  //   fromId
                  // });
                  openAccurateTab({
                    type: PageRoutesTypeEnum.PageTaskView,
                    key: row.taskId,
                    titleKey: row.taskNo,
                    fromId
                  })
                }
              }
            };
            return h('a', data, [row.taskNo])
          }
        },
        {
          label: t('common.label.taskTemplate'),
          field: 'templateName',
          width:120
        },
        {
          label: t('common.base.customer'),
          field: 'customerName'
        },
        {
          label: t('common.base.status'),
          field: 'state',
          width: 100,
          template: (row, field) => {
            let state = row.state;
            let stateValue = TaskStateEnum.getValue(state);

            return `<span class="stats-badge" style="background-color:${TaskStateEnum.getColor(stateValue)};">${state}</span>`;
          }
        },
        {
          label: t('common.label.principalName'),
          field: 'executorName',
          width: 150,
          render: (h, row, field) => {
            return (<div>{isOpenData && row.executorStaffId ? <open-data type="userName" openid={row.executorStaffId}></open-data> : row.executorName}</div>)
          }
        },
        {
          label: t('common.base.column.createPerson'),
          field: 'createUserName',
          width: 150,
          render: (h, row, field) => {
            return (<div>{isOpenData && row.createUserStaffId ? <open-data type="userName" openid={row.createUserStaffId}></open-data> : row.createUserName}</div>)
          }
        }
      ]
    },

    handlerTimePeriodChange(data){
    },

    // 重置
    handlerResetClick() {
      this.teamId = '';
      this.tag = [];
      this.periodValue.type = 'date'
      this.$nextTick(()=>{
        this.$set(this.periodValue, 'startTime', +nearDateBy(7))
        this.$set(this.periodValue, 'endTime', +dayTimeEnd(nearDateBy(1)))
        this.renderTrend();
      })
    },

    // 查询点击事件
    handlerSearchClick() {
      this.renderTrend();
    }
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
    isError() {
      return !this.periodValue.startTime || this.periodValue.endTime
    }
  },
  mounted(){
    this.handlerResetClick()
    // let initData = _init_data || {};
    // this.teams = initData.teams || [];
    this.initTrend();

    window.onresize = _.debounce(function(){
      trend.resize();
    }, 200)
  }
}
</script>

<style lang="scss">
.plan-trend-chart{
  line-height: 24px;
  padding: 15px;
  margin-bottom: 12px;
  border-radius: 4px;
  background:#fff;
}
.stats-trend-table-wrap{
  padding: 10px 50px 10px 80px;
}

.stats-trend-table-bar{
  display: flex;
  flex-flow: row nowrap;
  margin-bottom: 5px;

  h5{
    margin: 0;
    font-size: 14px;
    line-height: 24px;
    flex: 1;
  }

  .btn-sm{
    padding: 2px 20px;
  }

}
.stats-panel-trend {
  .base-table-cell {
    height: auto;
  }
}

.stats-panel-trend{
  .flex-box{
    display: flex;
    justify-content: flex-start;
  }
  .charts-search-block{
    margin-bottom: 12px;
    padding: 16px 0 0 0px;
    width: 100%;
    background: white;
    border-radius: 4px;
    display:flex;
    align-items: flex-end;
    .charts-search-block-content{
      width: 100%;
      .charts-search-item{
        position: relative;
        display: flex;
        align-items: center;
        margin: 0 16px 16px 0;
        .stats-team-select.biz-team-select{
          margin:0;
        }
        label{
          min-width: 70px;
          white-space: nowrap;
          margin:0;
        }
      }
      
      .error-row {
          width: 430px;
          left: 140px;
          top: 40px;
          right: 0;
          display: flex;
          align-items: center;
          justify-content: space-between;
          position: absolute;
          line-height: 20px;
          font-size: 12px;
          color: $color-danger;

          .start {
            flex: 1;
          }
          .end {
            flex: 1;
          }
        }
    }
    .charts-search-btn{
      display:flex;
      justify-content: flex-end;
    }
    .publink-date-period{
      .el-select{
        width:80px;
      }
      .publink-date-period-picker{
        display:flex;
        .el-date-editor{
          width:120px;
        }
      }
    }
  }
}
</style>
